package com.atom.app.lifecycle.base

import com.atom.app.lifecycle.bean.Account
import com.atom.app.lifecycle.bean.Record
import com.atom.module.mvvm.base.ApiModel
import com.tencent.mmkv.MMKV

object AppModel : ApiModel {

    val mmkv: MMKV = MMKV.defaultMMKV()

    var commonDB = AppDBCommon.getDatabase()

    private lateinit var accountDB: AppDBAccount

    override fun onCleared() {

    }

    // MMKV  user ---------------------------------------------------------------------------
    fun loadUser(): String = mmkv.getString(AppConfig.currentUser, "") ?: ""

    fun saveUser(uuid: String) {
        mmkv.putString(AppConfig.currentUser, uuid)
    }

    fun resetUser() {
        mmkv.remove(AppConfig.currentUser)
    }

    // DB Common Account ---------------------------------------------------------------------------
    suspend fun insertAccount(account: Account.Bean): Long {
        return commonDB.accountDao().insert(account)
    }

    suspend fun loadAccount(insert: Long) = commonDB.accountDao().selectSingleById(insert)

    suspend fun loadAccountByUUID(uuid: String) = commonDB.accountDao().selectSingleByUUID(uuid)

    // DB Account ---------------------------------
    fun initAccountDB(name: String) {
        accountDB = AppDBAccount.getDatabase(name)
    }

    suspend fun insertAccountTo(record: Record.Bean): Long {
        return accountDB.recordDAO().insert(record)
    }

    suspend fun selectAllRecord() = accountDB.recordDAO().selectAll()

}
